<template>
  <div style="padding-bottom: 20px;">
    <div class="">
      <!-- <h2 v-if="tableAddEdit === 'add'">新增</h2>
      <h2 v-else-if="tableAddEdit === 'edit'">编辑</h2>
      <h2 v-else-if="tableAddEdit === 'view'">查看</h2> -->
      <h2>
        退货申请单
        <span v-if="tableAddEdit === 'edit' || tableAddEdit === 'view'" style="margin-left: 20px;color: #200281;">{{
          Send.refundBatchNo }}</span>
      </h2>
    </div>
    <div style="width: 100%;border-bottom: 1px solid #000;">
      <h2><i class="el-icon-document"></i><span style="margin-left: 20px;font-weight: normal;">退货药品清单</span></h2>
    </div>
    <el-row :span="6" class="df" style="margin: 20px 0;">
      <el-col :span="6" style="display: flex;align-items: center">
        <span style="display: block;margin-right: 20px;">配送企业:</span>
        <el-select :disabled="tableAddEdit === 'view'" @change="changeCompany" v-model="selectedCompanyId" size="mini" :placeholder="Send.companyName">
          <el-option v-for="item in companyList" :key="item.id" :label="item.companyName" :value="item.id">
          </el-option>
        </el-select>
      </el-col>
      <el-button v-if="tableAddEdit === 'add' || tableAddEdit === 'edit'" @click="toAdd(false)" size="small" type="primary"><i class="el-icon-plus"></i>添加退货药品</el-button>
    </el-row>
    <el-alert size="mini" show-icon style="background-color: #d3deee;border: 1px solid #2558ac; color: #2558ac;font-size: 14px;">
      退货药品种类总数 <span class="number">{{ tableData.length }}</span> 项，总金额<span class="number">{{
        totalFee }}</span>元。
    </el-alert>
    <el-table height="300" :data="returnTableData" style="width: 100%;margin-top: 20px;" size="mini">
      <el-table-column prop="orderNo" label="订单号">
      </el-table-column>
      <el-table-column prop="batchName" label="集采批次" width="180">
      </el-table-column>
      <el-table-column prop="medicineNo" label="流水号">
      </el-table-column>
      <el-table-column prop="medicineName" label="通用名">
      </el-table-column>
      <el-table-column prop="categoryName" label="品种名称">
      </el-table-column>
      <el-table-column label="采购数量">
        <template slot-scope="scope">
          {{ scope.row.purchaseAmount }}
        </template>
      </el-table-column>
      <el-table-column prop="purchasePrice" label="采购价(元)">
      </el-table-column>
      <el-table-column prop="purchaseFee" label="采购金额(元)">
      </el-table-column>
      <el-table-column label="退货计量单位" prop="specification">
      </el-table-column>
      <el-table-column label="退货数量" prop="amount">
      </el-table-column>
      <el-table-column prop="fee" label="退货金额(元)">
      </el-table-column>
      <el-table-column label="操作" width="150" v-if="tableAddEdit === 'add' || tableAddEdit === 'edit'">
        <template slot-scope="scope">
          <el-button type="primary" slot="reference" size="mini" @click="toAdd(scope.row, scope.$index)">编辑</el-button>
          <el-button type="primary" v-if="tableAddEdit=='view'" slot="reference" size="mini" @click="toAdd(scope.row, scope.$index)">查看</el-button>
          <el-popconfirm style="margin: 0 10px;" :title="returnTableData.length == 1 ? '这是最后一条数据了,是否要删除' : '请确认是否删除'" @confirm="handleDelete(scope.row,scope.$index)" class="ml10">
            <el-button type="primary" slot="reference" size="mini">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <div class="block" style="margin: 20px 0;margin-left: 60%;">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="totalSize" :page-sizes="[10,20, 30, 40, 50]">
      </el-pagination>
    </div>
    <div style="display: flex;align-items: center;margin-bottom: 20px;">
      <span style="width: 80px;">
        退货原因:
      </span>
      <el-input :disabled="tableAddEdit === 'view'" v-model="Send.refundReason" size="mini" style="width: 60%;">
      </el-input>
    </div>
    <div style="display: flex; align-items: center;margin-bottom: 20px;"><span style="margin-right: 20px;">
        原因附件:</span>
      <uploadFile v-if="!Send.explainFile" v-model="returnReasonFile" :disabled="tableAddEdit === 'view'" />
      <a v-if="Send.explainFile" :href="Send.explainFile">退货清单盖章扫描件.pdf</a>
    </div>
    <el-dialog v-if="dialogVisible" :title="addEdit === 'edit' ? '编辑退货药品信息' : '新增退货药品'" :width="dialogScreen ? '' : '1000px'" :visible.sync="dialogVisible" append-to-body :beforeClose="changeTwoScreen">
      <AddReturns :choose="requestChoose" :addEdit="addEdit" :returnTableInfo="returnTableInfo" :flag2="dialogVisible" @chooseData="changeData" @changeTwo="changeDia">
      </AddReturns>
    </el-dialog>
    <div style="width:100%;display:flex;justify-content: center;align-items: center;">
      <el-button v-if="tableAddEdit === 'add' || (tableAddEdit === 'edit') && Send.status === 0" class="width" type="primary" style="margin-right: 60px;" plain @click="Staging(true)">暂存</el-button>
      <el-button class="width" v-if="tableAddEdit === 'add' || tableAddEdit === 'edit'" style="margin-right:60px" slot="reference" type="primary" size="small" @click="handleTop(false)">提交</el-button>
      <el-button class="width" size="small" @click="hide">取消</el-button>
    </div>
    <el-dialog :visible.sync="changeStoreVisible" class="taskDialog delete-shortcut-dialog" width="420px" :modal="false" :show-close="false" :close-on-click-modal="false" style="margin-top:40px">
      <template slot="title">
        <span style="font-size:16px;font-weight:400;color:red">
          <i class="iconfont icon-warning" style="font-size:20px;color:rgba(23,155,255,1);margin-right:5px;"></i>变更配送企业将清空当前退货清单！请确认！
        </span>
      </template>
      <div slot="footer" class="dialog-footer">
        <el-button @click="changeStoreCancle">取 消</el-button>
        <el-button type="primary" @click="changeStoreForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getDetail, saveOrderRefund, removeOrder } from "../../api/businessTwo/orderRefund";
import { getList } from "../../api/businessTwo/order";
import { mapGetters } from 'vuex';
import AddReturns from "../../components/orderRefund/AddReturns.vue";
import { getToken } from '@/util/auth';
import uploadFile from '@/components/uploadFile/uploadFile.vue'

export default {
  components: {
    AddReturns,
    uploadFile,
  },
  props: {
    Send: {
      type: Object,
    },
    flag: {
      type: Boolean
    },
    tableAddEdit: {
      type: String
    },
  },
  data () {
    return {
      requestChoose: false,
      selectedCompanyId: '',
      changeStoreVisible: false,
      beforeStorageValue: '',
      afterStorageValue: '',
      refundReason: '',
      companyInfo: {},
      dialogScreen: false,
      cities: [],
      dialogVisible: false,
      returnTableInfo: {},
      pageSize: 10,
      tableData1: [],
      totalSize: 0,
      form1: null,
      value2: null,
      value4: '',
      num: 0,
      priceSum: 0,
      currentPage: 1,
      value: '',
      uploadUrl: "",
      form: [
      ],
      returnTableData: [],
      tableData: [],//记录实际table总数
      companyList: [],
      addEdit: 'add',
      editIndex: 0,
      totalFee: 0,
      returnReasonFile: [],
      selectedCompanyList: []
    }
  },
  created () {
    this.getChange()
    this.firstTo()
  },
  computed: {
    ...mapGetters(["userInfo"]),
  },
  watch: {
    selectedCompanyId: {
      immediate: true,
      handler (val, old) {
        console.log('val:', val, 'old:', old)
        if (this.beforeStorageValue) {
          console.log(
            'val:',
            val,
            'old:',
            old,
            'this.beforeStorageValue',
            this.beforeStorageValue
          )
          if (val !== this.beforeStorageValue) {
            this.changeStoreVisible = true
          }
        }
      }
    }
  },
  mounted () {
    // this.beforeStorageValue = this.selectedCompanyId
  },
  methods: {
    changeCompany (id) {
      this.selectedCompanyList.push(id)
      if (this.selectedCompanyList.length > 2) {
        this.selectedCompanyList.splice(2, this.selectedCompanyList.length)
      }
      this.companyList.forEach(item => {
        if (id === item.id) {
          this.companyInfo.selectedCompanyName = item.companyName
          this.companyInfo.selectedCompanyId = item.id
        }
      })
      // this.returnTableData = []
      if (this.tableData.length) {
        this.changeStoreVisible = true
      }
    },
    getChange () {
      getList().then((res) => {
        let data = res.data.data.records
        this.companyList = this.saveUnique(data, 'companyName')
      })
    },
    changeStoreCancle () {
      this.selectedCompanyId = this.selectedCompanyList[0]
      this.changeStoreVisible = false
      // this.selectedCompanyId = this.beforeStorageValue
      // this.changeStoreVisible = false
      // if (!this.Send.instName) {
      //   this.companyInfo.value = this.selectedCompanyId
      //   this.companyList.map((v) => {
      //     if (this.selectedCompanyId == v.value) {
      //       this.companyInfo.label = v.label
      //     }
      //     console.log(this.companyInfo);
      //   })
      // }
    },
    changeStoreForm () {
      // this.beforeStorageValue = this.selectedCompanyId // 确定更改后使中介值等于目前框内的值，这样下次确定改变取消的话，可以回到现在的值
      // this.changeStoreVisible = false
      // if (!this.Send.instName) {
      // this.companyInfo.value = this.selectedCompanyId
      // this.companyList.map((v) => {
      //   if (this.selectedCompanyId == v.value) {
      //     this.companyInfo.label = v.label
      //   }
      //   console.log(this.companyInfo);
      // })
      // }
      this.tableData = []
      this.returnTableData = []
      this.changeStoreVisible = false
      this.totalSize = 0
      this.totalFee = 0
    },
    firstTo () {
      if (this.tableAddEdit === 'add') {
        this.companyInfo.selectedCompanyId = this.selectedCompanyId
        this.companyList.map((v) => {
          if (this.selectedCompanyId == v.id) {
            this.companyInfo.selectedCompanyName = v.companyName
          }
        })
      } else if (this.tableAddEdit === 'edit' || this.tableAddEdit === 'view') {
        this.returnTableInfo = this.Send
        console.log('%c [ this.Send ]-245', 'font-size:13px; background:#4d38b0; color:#917cf4;', this.Send)
        this.selectedCompanyId = this.Send.companyName
        this.companyInfo.selectedCompanyName = this.Send.companyName
        this.companyInfo.selectedCompanyId = this.Send.companyId
        this.returnReasonFile = this.Send.explainFile || []
        this.getList()
      }
    },
    toAdd (record, index) {
      if (!record) {
        if (!this.selectedCompanyId) {
          this.$message.warning('请选择配送企业')
          return
        }
        this.addEdit = 'add'
        this.returnTableInfo = this.companyInfo
      } else {
        this.addEdit = 'edit'
        this.requestChoose = true
        this.returnTableInfo = record
        this.editIndex = index
      }
      this.dialogVisible = !this.dialogVisible
    },
    handleUploadSuccess (response, row, rowInfo) {
      // 处理上传成功后的响应数据
      console.log(response, row, rowInfo);
      console.log("上传成功！", response);
      // 保存返回结果到某个变量
      rowInfo.invoiceFile = response.data.name;
      console.log(row);
    },
    handleUploadSuccess1 (response, row) {
      // 处理上传成功后的响应数据
      console.log("上传成功！", response);
      // 保存返回结果到某个变量
      this.uploadUrl = response.data.name;
      console.log(row);
    },
    async getList () {
      let res = await getDetail({
        current: this.currentPage,
        size: this.pageSize,
        refundBatchNo: this.Send.refundBatchNo,
        companyName: this.Send.companyName
      })
      this.tableData = res.data.data.orderRefundVOS
      let returnTableData = res.data.data.orderRefundVOS
      if (returnTableData.length <= 10) {
        this.returnTableData = returnTableData
      } else if (returnTableData.length > 10) {
        this.returnTableData = returnTableData.slice(0, 10)
      }
      let totalFee = 0
      this.tableData.forEach(item => {
        totalFee += Number(item.fee)
      })
      this.totalFee = totalFee
      this.totalSize = res.data.data.total
    },
    handleTop () {
      let arr = []
      console.log(this.tableData);
      this.tableData.forEach((v) => {
        arr.push({
          specification: v.specification,
          id: v.id || null,
          shotType: v.shotType,
          invoiceFile: v.invoiceFile,
          batchId: v.batchId,
          refundBatchId: this.Send.id || null,
          refundBatchNo: this.Send.refundBatchNo || null,
          orderId: v.orderId,
          orderNo: v.orderNo,
          instId: v.instId,
          instName: v.instName,
          instNo: v.instNo,
          medicineNo: v.medicineNo,
          medicineName: v.medicineName,
          chargeUnit: v.chargeUnit,
          amount: v.amount,
          purchaseAmount: v.purchaseAmount,
          purchaseFee: v.purchaseFee,
          purchasePrice: v.purchasePrice,
          fee: v.fee,
          invoiceNo: v.invoiceNo,
          reason: v.reason,
          deliveryCompanyId: v.deliveryCompanyId,
          deliveryCompanyName: v.deliveryCompanyName
        })
      })
      console.log(arr);
      console.log('%c [ this.returnReasonFile ]-343', 'font-size:13px; background:#664d99; color:#aa91dd;', this.returnReasonFile)

      if (this.returnReasonFile.length == 0) {
        return this.$message.error("请上传退货附件")
      }
      let params = {
        orderRefunds: arr,
        isDraft: false,
        refundReason: this.refundReason,
        explainFile: this.returnReasonFile[0].negativeInvoiceFile,
        id: this.Send.id
      }
      console.log(this.returnReasonFile[0]);
      saveOrderRefund(params).then((res) => {
        this.$message.success(`提交成功`);
        this.hide()
        console.log(res);

      })

      console.log(this.tableData);

    },
    Staging () {
      let arr = []
      console.log(this.tableData);
      this.tableData.forEach((v) => {
        arr.push({
          shotType: v.shotType,
          specification: v.specification,
          invoiceNo: v.invoiceNo || null,
          invoiceFile: v.invoiceFile || null,
          id: v.id || null,
          batchId: v.batchId,
          refundBatchId: this.Send.id || null,
          refundBatchNo: this.Send.refundBatchNo || null,
          orderId: v.orderId,
          orderNo: v.orderNo,
          instId: v.instId,
          instName: v.instName,
          instNo: v.instNo,
          medicineNo: v.medicineNo,
          medicineName: v.medicineName,
          chargeUnit: v.chargeUnit,
          amount: v.amount,
          fee: v.fee,
          reason: v.reason,
          deliveryCompanyId: v.deliveryCompanyId,
          deliveryCompanyName: v.deliveryCompanyName
        })
      })
      saveOrderRefund({
        orderRefunds: arr,
        isDraft: true,
        refundReason: this.refundReason,
        explainFile: this.returnReasonFile[0] && this.returnReasonFile[0].url,
      }).then(() => {
        this.$message.success(`暂存成功`);
        this.hide()
      })

    },
    changeTwoScreen () {

      this.dialogScreen = false
      this.dialogVisible = false
      this.requestChoose = false
      this.returnTableInfo = {}
    },
    changeDia (data) {
      this.requestChoose = data
      this.dialogVisible = data
      this.returnTableInfo = {}
    },
    fileUrl () {
      return `/api/blade-resource/oss/endpoint/put-file?${this.website.tokenHeader}=${getToken()}`
    },
    changeData (data) {
      this.dialogVisible = false
      if (this.addEdit === 'add') {
        data.id = null
        console.log(data);
        this.tableData.unshift(data)
        // 测试时为了一次性增加21条数据，方便快速测试
        // this.tableData.unshift(data)
        // this.tableData.unshift(data)
        // this.tableData.unshift(data)
        // this.tableData.unshift(data)
        // this.tableData.unshift(data)
        // this.tableData.unshift(data)
        // this.tableData.unshift(data)
        // this.tableData.unshift(data)
        // this.tableData.unshift(data)
        // this.tableData.unshift(data)
        // this.tableData.unshift(data)
        // this.tableData.unshift(data)
        // this.tableData.unshift(data)
        // this.tableData.unshift(data)
        // this.tableData.unshift(data)
        // this.tableData.unshift(data)
        // this.tableData.unshift(data)
        // this.tableData.unshift(data)
        // this.tableData.unshift(data)
        // this.tableData.unshift(data)
        this.returnTableData = this.tableData.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize)
        this.$message.success('新增成功');
      } else {
        this.$set(this.returnTableData, this.editIndex, data)
        this.tableData.splice(this.pageSize * (this.currentPage - 1) + this.editIndex, this.pageSize * (this.currentPage - 1) + this.editIndex + 1, data)
        this.$message.success('编辑成功');
      }
      let totalFee = 0
      this.tableData.forEach(item => {
        totalFee += Number(item.fee)
      })
      this.totalFee = totalFee
      this.totalSize = this.tableData.length
    },
    handleCurrentChange (val) {
      this.currentPage = val
      this.returnTableData = this.tableData.slice((val - 1) * this.pageSize, val * this.pageSize)
    },
    handleSizeChange (val) {
      this.pageSize = val
      let pageTotal = Math.ceil(this.tableData.length / this.pageSize)
      if (pageTotal < this.currentPage) {
        this.currentPage = pageTotal
      }
      this.returnTableData = this.tableData.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize)
    },
    async handleDelete (row, index) {
      if (this.tableAddEdit === 'edit') {
        if (row.id) {
          try {
            await removeOrder(row.id)
          } catch (error) {
            return
          }
        }
      }
      this.tableData.splice((this.currentPage - 1) * this.pageSize + index, 1)
      this.totalSize = this.tableData.length
      let totalPageSize = Math.ceil(this.tableData.length / this.pageSize)
      if (totalPageSize < this.currentPage) {
        this.currentPage--
      }
      this.returnTableData = this.tableData.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize)
      let totalFee = 0
      this.tableData.forEach(item => {
        totalFee += Number(item.fee)
      })
      this.totalFee = totalFee
      if (this.tableData.length == 0) {
        this.hide()
      }
      this.$message.success('删除成功！')
    },
    hide () {
      this.$emit("changeTwo", false)
    },
    saveUnique (arr, key) {
      let newArr = [];
      let obj = {};
      for (var i = 0; i < arr.length; i++) {
        if (!obj[arr[i][key]]) {
          newArr.push(arr[i])
          obj[arr[i][key]] = true
        }
      }
      return newArr
    },
  }
}
</script>

<style lang="scss" scoped>
.df {
  display: flex;
  align-items: center;
}

.jcsb {
  justify-content: space-between;
}

.el-table {
  margin-bottom: 30px;
}

.ml {
  margin-left: 60px;
}

::v-deep th {
  background-color: #f1f1f1;
}

::v-deep .el-table__cell {
  height: 50px !important;
}

h2 {
  font-size: 18px;
}

.width {
  width: 120px;
  height: 36px;
}

.ret {
  margin-left: 30%;
  margin-right: 60px;
}

.number {
  font-size: 16px;
  color: #2558ac;
}

::v-deep th.el-table__cell {
  background-color: #fafafa;
}

::v-deep .el-table__cell {
  border-right: 1px solid #ebeef5 !important;
  text-align: center;
}

::v-deep .cell {
  display: flex;
  justify-content: center;
}

.approvalStage {
  background-color: #fff;
  padding: 20px;
  padding-bottom: 40px;
  border-radius: 4px;
}
::v-deep .el-alert {
  padding: 4px 16px !important;
}
::v-deep .el-alert__icon.is-big {
  font-size: 22px !important;
}
::v-deep .el-alert__description {
  margin: 0;
}
</style>
